package com.hnevc.myapplication02;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,View.OnKeyListener {
ImageButton[] buttons=new ImageButton[2];//声明一个长度为2的数组
    private TextView tv_choose,tv_info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取两个按钮的引用
        buttons[0]=(ImageButton) findViewById(R.id.ib_img1);
        buttons[1]=(ImageButton) findViewById(R.id.ib_img2);
        tv_choose=(TextView) findViewById(R.id.tv_choose);
        tv_info=(TextView)findViewById(R.id.tv_info);
        tv_info.setText("请选择下列两张图中的一张作为背景");
        for (ImageButton button:buttons){
            button.setOnClickListener(this);//添加点击事件监听器
            button.setOnKeyListener(this);//添加键盘事件监听器
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_img1:
                tv_choose.setText("你选择了A");
                break;
            case R.id.ib_img2:
                tv_choose.setText("你选择了B");
                break;
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_A:
                buttons[0].performClick();
                buttons[0].requestFocus();
                break;
            case KeyEvent.KEYCODE_B:
                buttons[1].performClick();
                buttons[1].requestFocus();
                break;
        }
        return false;
    }
}